package promotion

import (
	// "bp/cache"
	sqlc "bp/db/sqlc"
	"bp/internal/util"
	"context"
	"database/sql"
)

// EnsurePromotionStatParam 确保PromotionStat参数
type EnsurePromotionStatParam struct {
	PromotionPtr *sqlc.Promotion
	PromotionID  int64
}

// EnsurePromotionStat 确保PromotionStat对于一个活动始终有一条记录
func (s *PromotionEntityServiceImp) EnsurePromotionStat(ctx context.Context, q *sqlc.Queries, withLock bool, ptr *EnsurePromotionStatParam) (promotionStatPtr *sqlc.PromotionStat, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	var promotionPtr *sqlc.Promotion
	if ptr.PromotionPtr != nil {
		promotionPtr = ptr.PromotionPtr
	} else {
		promotionPtr, err = s.GetPromotionPtr(ctx, q, ptr.PromotionID)
		if err != nil {
			return
		}
		slog.Infof("0 GetPromotionPtr ok")
	}
	promotionID := promotionPtr.ID

	var sqlErr error
	var promotionStat sqlc.PromotionStat
	if withLock {
		promotionStat, sqlErr = q.GetPromotionStatByPromotionIDToLock(ctx, promotionID)
	} else {
		promotionStat, sqlErr = q.GetPromotionStatByPromotionID(ctx, promotionID)
	}

	if sqlErr != nil {
		if sql.ErrNoRows != sqlErr {
			err = sqlErr
			return
		}
		promotionStat, err = q.UpsertPromotionStat(ctx, sqlc.UpsertPromotionStatParams{
			BrandID:     promotionPtr.BrandID,
			PromotionID: promotionID,
		})
		if err != nil {
			return
		}
	}
	promotionStatPtr = &promotionStat
	slog.Infof("确保PromotionStat对于一个活动始终有一条记录并返回 ok")
	return
}
